/**
* @Description:
* @Author: yanhui.gao
* @Date: 2019/7/24  14:45
*/
<template>
  <div class="editable-cell">
    <div v-if="editable" :class="['editable-cell-input-wrapper', singleEdit ? 'single-edit' : '']">
      <a-form :form="form">
        <a-form-item :colon="false" class="no-validate">
          <j-popup
            v-decorator="decorator"
            :code="dictCode"
            org-fields="number,name,id"
            dest-fields="number,name,id"
            v-if="showFormItem('jpop')"
            @ok="jpopCallBack"
            @callback="handleChange"
            field="id" />
          <j-dict-select-tag
            v-if="showFormItem('selectTag')"
            :placeholder="placeholder"
            v-decorator="decorator"
            :dictCode="dictCode"
            :format="format"
            :disabled="disable"
            @change="handleChange"
          />
          <a-textarea
            v-if="showFormItem('textarea')"
            v-decorator="decorator"
            :placeholder="placeholder"
            :disabled="disable"
            @change="handleChange"
          />
          <a-time-picker
            v-if="showFormItem('startTime')"
            v-decorator="decorator"
            :placeholder="placeholder"
            @change="handleChange"
            :format="timeFormat"
            :disabled-hours="getDisableStartHours"
            :disabled-minutes="getDisableStartMinutes"
            :disabled-seconds="getDisableStartSeconds"
            :disabled="disable"
            :allowClear="false"
            style="width: 100%"
          />
          <a-time-picker
            v-if="showFormItem('endTime')"
            v-decorator="decorator"
            :placeholder="placeholder"
            @change="handleChange"
            :format="timeFormat"
            :disabled="disable"
            :allowClear="false"
            :disabled-hours="getDisableHours"
            :disabled-minutes="getDisableMinutes"
            :disabled-seconds="getDisabledSeconds"
            style="width: 100%"
          />
          <a-date-picker
            :format="format"
            v-if="showFormItem('datePickerStart')"
            v-decorator="decorator"
            :placeholder="placeholder"
            :disabled="disable"
            :show-time="{ defaultValue: moment('08:00:00', 'HH:mm:ss') }"
            :drawStartTime="drawStartTime"
            :disabled-date="(current) => disabledDateStart(current)"
            @change="handleChange"
            :allowClear="false"
          />
          <a-date-picker
            :format="format"
            v-if="showFormItem('datePickerEnd')"
            v-decorator="decorator"
            :placeholder="placeholder"
            :show-time="{ defaultValue: moment('22:00:00', 'HH:mm:ss') }"
            :disabled="disable"
            :drawStartTime="drawStartTime"
            :allowClear="false"
            :drawEndTime="drawEndTime"
            :disabled-date="disabledDate"
            @change="handleChange"
            @ok="handleChange"
          />
          <a-input
            v-if="showFormItem('input')"
            v-decorator="decorator"
            :placeholder="placeholder"
            @change="handleChange"
            autocomplete="off"
            @blur="focusChange"
          />
          <a-input-number
            :min="min"
            :max="max"
            v-if="showFormItem('number')"
            v-decorator="decorator"
            :placeholder="placeholder"
            @change="handleChange"
            @blur="focusChange"
            :disabled="disable"
            style="width: 100%"
          />
          <a-switch
            v-if="showFormItem('switch')"
            v-decorator="decorator"
            :placeholder="placeholder"
            @change="handleChange"
            :value="value"
          />

          <a-range-picker
            :showTime="showTime"
            :format="format"
            v-if="showFormItem('rangePicker')"
            v-decorator="decorator"
            @change="handleChange"
          />
          <a-month-picker
            :showTime="showTime"
            :format="format"
            v-if="showFormItem('monthPicker')"
            v-decorator="decorator"
            :placeholder="placeholder"
          />
          <a-select
            v-if="showFormItem('select')"
            v-decorator="decorator"
            :placeholder="placeholder"
            @change="handleChange"
            :mode="selectMode"
            :labelInValue="selectLabelInValue"
          >
            <slot />
          </a-select>
          <a-auto-complete
            v-if="showFormItem('autoComplete')"
            v-decorator="decorator"
            :placeholder="placeholder"
            @search="handleSearch"
            optionLabelProp="text"
            :disabled="notEdit"
          >
            <template slot="dataSource">
              <slot />
            </template>
          </a-auto-complete>
        </a-form-item>
      </a-form>
      <a-icon v-if="singleEdit" type="check" class="editable-cell-icon-check" @click="check(true)" />
    </div>
    <div v-else :class="['editable-cell-text-wrapper', singleEdit ? 'single-edit' : '']">
      {{ getText || ' ' }}
      <a-icon v-if="singleEdit" type="edit" class="editable-cell-icon" @click="edit" />
    </div>
  </div>
</template>
<script>
import moment from 'moment'
import JPopup from '@/components/jeecg/JPopup'

export default {
  data() {
    return {
      form: this.$form.createForm(this),
      editable: this.defaultEditable
    }
  },
  components: {
    JPopup
  },
  props: {
    // 非编辑模式下，显示文本
    text: {
      type: [Number, String, Array, Object]
    },
    // 编辑模式下组件值
    value: {
      message: { type: [Number, String, Array, Object], default: '' }
    },
    disable: Boolean,
    // 表单组件类型
    formType: {
      validator(value) {
        return (
          [
            'jpop',
            'input',
            'number',
            'switch',
            'rangePicker',
            'select',
            'monthPicker',
            'autoComplete',
            'selectTag',
            'startTime',
            'endTime',
            'datePickerStart',
            'datePickerEnd',
            'textarea'
          ].indexOf(value) !== -1
        )
      },
      default: 'input'
    },
    // 表单校验
    decoratorOptions: {
      type: [Array, Object]
    },
    min: { type: Number, default: -Infinity },
    max: { type: Number, default: Infinity },
    minNumber: { type: Number, default: 0 },
    maxNumber: { type: Number, default: 0 },
    // 表单默认提示
    placeholder: { type: String, default: '请输入' },
    // 支持单元格单个编辑
    singleEdit: { type: Boolean, default: false },
    // 默认编辑模式
    defaultEditable: { type: Boolean, default: false },
    // 是否自动保存
    autoSave: { type: Boolean, default: false },
    // 日期组件设置
    format: { type: String, default: 'YYYY-MM-DD hh:mm:ss' },
    showTime: { type: [Boolean, Object], default: false },
    // 是否可编辑
    notEdit: { type: Boolean, default: false },
    // 选择框是否多选
    selectMode: { type: String, default: undefined },
    // 多选选择框属性
    selectLabelInValue: { type: Boolean, default: true },
    // 多选选择框默认值
    selectDefaultValue: { type: Array },
    //字典数据类型
    dictCode: { type: String, default: undefined },
    //开始时间
    startTime: {},
    //结束时间
    endTime: {},
    //提货开始日期
    datePickerStart: {},
    drawStartTime: '',
    //提货结束日期
    datePickerEnd: {},
    drawEndTime: '',
    timeFormat: { type: String, default: 'HH:mm:ss' }
  },
  computed: {
    // 格式化文本
    getText() {
      if (typeof this.text === 'function') {
        return this.text()
      }
      return this.text
    },
    // 根据属性，合成表单验证装饰器
    decorator: {
      get() {
        if (this.decoratorOptions) {
          let itemDecorator = []
          if (this.minNumber > 0) {
            itemDecorator = [
              'formName',
              {
                initialValue: this.value,
                rules: [
                  {
                    required: true,
                    message: '请输入原价'
                  },
                  { validator: this.rightOriginalPrice }
                ]
              }
            ]
          } else if (this.maxNumber > 0) {
            itemDecorator = [
              'formName',
              {
                initialValue: this.value,
                rules: [
                  {
                    required: true,
                    message: '请输入原价'
                  },
                  { validator: this.rightPrice }
                ]
              }
            ]
          } else {
            itemDecorator = [
              'formName',
              {
                initialValue: this.value,
                ...this.decoratorOptions
              }
            ]
          }
          return itemDecorator
        }
        const itemDecorator = [
          'formName',
          {
            initialValue: this.value
          }
        ]

        return itemDecorator
      },
      set(value) {
        this.decorator[1].initialValue = value.trim() // 最后修改了msg
      }
    }
  },
  watch: {
    // 监视父页面是否可编辑属性，及时响应控件内切换
    defaultEditable(value) {
      this.editable = value
    }
  },
  methods: {
    moment,
    // 判断表单是否
    showFormItem(formType) {
      return this.formType === formType
    },
    rightPrice(rule, value, callback) {
      const form = this.form
      if (this.maxNumber > 0) {
        if (value != '' && value > this.maxNumber) {
          callback('售价要小于原价！')
        } else {
          callback()
        }
      }
    },
    rightOriginalPrice(rule, value, callback) {
      const form = this.form
      if (this.minNumber > 0) {
        if (value != '' && value < this.minNumber) {
          callback('原价要大于售价！')
        } else {
          callback()
        }
      }
    },
    // 表单change事件
    handleChange(value, dateString) {
      console.log('value', value)
      if (this.autoSave) {
        if (this.formType === 'input') {
          this.$emit('valueChange', value.target.value)
        } else if (this.formType === 'select') {
          this.$emit('selectChange', value)
        } else if (this.formType === 'number') {
          this.$emit('numberChange', value)
        } else if (this.formType === 'startTime') {
          this.$emit('startTimeChange', value)
        } else if (this.formType === 'endTime') {
          this.$emit('endTimeChange', value)
        } else if (this.formType === 'datePickerStart') {
          this.$emit('datePickerStartChange', [value, dateString])
        } else if (this.formType === 'datePickerEnd') {
          this.$emit('datePickerEndChange', [value, dateString])
        } else if (this.formType === 'selectTag') {
          this.$emit('selectTagChange', value)
        } else if (this.formType === 'textarea') {
          this.$emit('textareaChange', value.target.value)
        } else if (this.formType === 'rangePicker') {
          this.$emit('rangePickerChange', value)
        } else if (this.formType === 'jpop') {
          this.$emit('jpopChange', value)
        }
      }
      // this.check(false);
    },
    // auto-complete 搜索
    handleSearch(value) {
      this.$emit('autoCompleteSearch', value)
    },

    // 表单校验
    validate() {
      const result = {
        success: false,
        value: ''
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          if (!this.editable) {
            result.value = this.getText
          } else {
            result.value = values.formName
          }
          result.success = true
        }
      })
      return result
    },
    // 表单赋值
    setValue(value) {
      this.form.setFieldsValue({
        formName: value
      })
    },
    // 点击"对号"图标，校验通过后触发通知父组件
    check(flag) {
      this.form.validateFields((err, values) => {
        if (!err) {
          if (flag) {
            // 切换到只读模式
            this.editable = false
          }
          this.$emit('valueChange', values.formName)
        }
      })
    },
    getDisableStartHours() {
      const Hours = Array.from(Array(24), (v, k) => k)
      if (this.endTime) {
        let h = this.endTime.hour()
        return Hours.slice(h + 1, Hours.length)
      }
      return []
    },
    getDisableStartMinutes(selectedHour) {
      const Minutes = Array.from(Array(60), (v, k) => k)
      if (this.endTime) {
        if (this.startTime && selectedHour < this.endTime.hour()) return []
        let m = this.endTime.minute()
        return Minutes.slice(m + 1, Minutes.length)
      }
      return []
    },
    getDisableStartSeconds(selectedHour, selectedMinute) {
      const Seconds = Array.from(Array(60), (v, k) => k)
      if (this.endTime) {
        if (this.startTime && selectedHour < this.endTime.hour()) return []
        if (this.startTime && selectedMinute < this.endTime.minute()) return []
        let s = this.endTime.second()
        return Seconds.slice(s, Seconds.length - 1)
      }
      return []
    },

    getDisableHours() {
      const Hours = Array.from(Array(24), (v, k) => k)
      if (this.startTime) {
        let h = this.startTime.hour()
        return Hours.slice(0, h)
      }
      return []
    },
    getDisableMinutes(selectedHour) {
      const Minutes = Array.from(Array(60), (v, k) => k)

      if (this.startTime) {
        if (this.endTime && selectedHour > this.startTime.hour()) return []
        let m = this.startTime.minute()
        return Minutes.slice(0, m)
      }
      return []
    },
    getDisabledSeconds(selectedHour, selectedMinute) {
      const Seconds = Array.from(Array(60), (v, k) => k)
      if (this.startTime) {
        if (this.endTime && selectedHour > this.startTime.hour()) return []
        if (this.endTime && selectedMinute > this.startTime.minute()) return []
        let s = this.startTime.second()
        return Seconds.slice(0, s + 1)
      }
    },
    // 切换到编辑模式
    edit() {
      this.editable = true
      this.decorator = this.value.trim()
    },
    jpopCallBack(e) {
      console.log('e', e)
    },
    disabledDateStart(current) {
      // const startDate = this.drawStartTime
      // const endDate = this.drawEndTime
      // console.log(this.drawStartTime)
      // console.log(drawEndTime)
      /* return (
        (current && current < moment('2022-06-10')) ||
        current > moment('2022-06-15')
      ) */
      if (this.drawEndTime) {
        // return current && current < moment(this.drawEndTime).subtract(1, 'days').endOf('day')
        return (
          (current && current < moment(this.drawStartTime)) ||
          current > moment(this.drawEndTime)
        )
      }
      // return current && current < moment().subtract(1, 'days')
      return current && current < moment(this.drawStartTime)
    },

    disabledDate(current) {
      if (this.drawStartTime) {
        return current && current < moment(this.drawStartTime).subtract(1, 'days').endOf('day')
      }
      return current && current < moment().subtract(1, 'days')
    },
    range(start, end) {
      const result = []
      for (let i = start; i < end; i++) {
        result.push(i)
      }
      return result
    },
    focusChange(e) {
      console.log('失去焦点')
      this.$emit('truefalseChange', e)
    }
    // disabledDateTime(dates, partial) {
    //   if (this.drawStartTime) {
    //     let hours = this.drawStartTime.split(' ')[1].split(':')[0]
    //     let minutes = this.drawStartTime.split(' ')[1].split(':')[1]
    //     let seconds = this.drawStartTime.split(' ')[1].split(':')[2]
    //     return {
    //       disabledHours: () => this.range(0, hours),
    //       disabledMinutes: () => this.range(0, minutes),
    //       disabledSeconds: () => [0, 60],
    //     }
    //   }
    //   // /* let hours = moment().hours();//0~23
    //   // let minutes = moment().minutes();//0~59
    //   // let seconds = moment().seconds();//0~59
    //   // //当日只能选择当前时间之后的时间点
    //   // if (dates&&moment(dates[1]).date() === moment().date()&&partial=='end') {
    //   //   return {
    //   //     disabledHours: () => this.range(hours+1,23),
    //   //     disabledMinutes: () => this.range(minutes+1,59),
    //   //     disabledSeconds: () => this.range(seconds+1,59),
    //   //   };
    //   // } */
    //   // /* return {
    //   //   disabledHours: () => this.range(0, 24).splice(4, 20),
    //   //   disabledMinutes: () => this.range(30, 60),
    //   //   disabledSeconds: () => [55, 56],
    //   // }; */
    // },
  },
  created() {
  }
}
</script>

<style scoped>
.editable-cell {
  position: relative;
  margin-top: -9px;
  margin-bottom: -9px;
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}

.editable-cell-input-wrapper.single-edit,
.editable-cell-text-wrapper.single-edit {
  padding-right: 24px;
}

.editable-cell-icon,
.editable-cell-icon-check {
  position: absolute;
  right: 0;
  width: 20px;
  cursor: pointer;
}

.editable-cell-icon {
  top: 3px;
  line-height: 18px;
  display: none;
}

.editable-cell-icon-check {
  top: 12px;
}

.no-validate {
  margin-bottom: 0;
}
</style>
